from rest_framework import serializers
from goods.models import SKU

class CartSerializer(serializers.Serializer):
    sku_id = serializers.IntegerField(min_value=1, label="商品编号")
    count = serializers.IntegerField(min_value=1, max_value=200, label="数量")
    selected = serializers.BooleanField(default=True, required=False)

    # 1.多字段校验
    def validate(self, attrs):
        # 1.获取数据
        sku_id = attrs["sku_id"]
        count = attrs["count"]

        # 2.判断商品是否存在
        try:
            sku = SKU.objects.get(id=sku_id)
        except Exception as e:
            raise serializers.ValidationError("商品不存在")
        # 3.判断count是否大于了库存量
        if count > sku.stock:
            raise serializers.ValidationError("库存量不足")

        # 4.返回
        return attrs


class CartDeleteSerializer(serializers.Serializer):
    sku_id = serializers.IntegerField(min_value=1, label="商品编号")

    # 1.单子段校验
    def validate_sku_id(self, sku_id):
        # 1.获取sku_id对应的对象是否存在
        try:
            SKU.objects.get(id=sku_id)
        except Exception as e:
            raise serializers.ValidationError("商品不存在")

        # 2.返回
        return sku_id

